package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {



    @Autowired
    ArticleFeign articleFeign;
    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //判断关注Operation的合法性
        if (dto.getOperation()==null||dto.getOperation()<0||dto.getOperation()>1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断作者的存在性
        if(dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"作者信息不能为空");
        }
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if(apAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"作者不存在");
        }

        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"未登录,请登录先");
        }

        if(dto.getOperation()==0){
            return followByUserId(user.getId(),dto.getArticleId(),apAuthor.getUserId());
        }else{
            //取消关注
            return followCancelByUserId(user.getId(),apAuthor.getUserId());
        }

    }

    /**
     * 取消关注的方法
     * @param followUserId
     * @param userId
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {
        //删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId,followUserId)
                .eq(ApUserFollow::getUserId,userId)
        );
        //删除作者端粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId,userId)
                .eq(ApUserFan::getUserId,followUserId)
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;


    /**
     * 关注的方法
     * @param userId
     * @param articleId
     * @param followUserId
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Long articleId, Integer followUserId){



        //获取被关注的作者对应的followUser
        ApUser followUser = apUserMapper.selectById(followUserId);
        if(followUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"关注用户不存在");
        }
        if(userId.intValue()==followUser.getId().intValue()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"不能关注自己");
        }
        //保存当前用户关注信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getId, followUser.getId())
                .eq(ApUserFollow::getUserId, userId)
        );
        if(apUserFollow==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setCreatedTime(new Date());
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setUserId(userId);
        apUserFollow.setIsNotice(true);
        apUserFollow.setLevel((short) 1);
        apUserFollowMapper.insert(apUserFollow);

        //在作者一边保存粉丝信息

        //先查后加
        ApUserFan apUserFan = apUserFanMapper.selectById(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId)
        );
        if(apUserFan!=null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //保存
        apUserFan = new ApUserFan();
        apUserFan.setCreatedTime(new Date());
        apUserFan.setFansId(userId.longValue());

        ApUser apUser = apUserMapper.selectById(userId);
        String name = apUser.getName();
        apUserFan.setFansName(name);
        apUserFan.setIsDisplay(true);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setLevel((short) 0);
        apUserFan.setUserId(followUserId);

        apUserFanMapper.insert(apUserFan);

        //TODO 记录用户行为
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setFollowId(followUserId);
        dto.setArticleId(articleId);
        dto.setUserId(apUser.getId());
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
